package cn.jxufe.imp;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jxufe.bean.Message;
import cn.jxufe.dao.SeedBagDAO;
import cn.jxufe.dao.SeedDAO;
import cn.jxufe.dao.UserDAO;
import cn.jxufe.entity.Seed;
import cn.jxufe.entity.SeedBag;
import cn.jxufe.entity.User;
import cn.jxufe.service.SeedBagService;

@Service
public class SeedBagImp implements SeedBagService{
	@Autowired
	SeedBagDAO seedBagDAO;
	
	@Autowired
	SeedDAO seedDAO;
	
	@Autowired
	UserDAO userDAO;
	
	@Override
	public List<SeedBag> getList(int userId) {
		return seedBagDAO.findByUserId(userId);
	}

	@Override
	public Message buySeed(HttpSession session, SeedBag seedBag) {
		Message message = new Message();
		message.setCode(0);
		try {
			User user = (User) session.getAttribute("curUser");
			if(user == null) {
				message.setMsg("您还未登录，请先登录！");
				return message;
			}
			int money = user.getMoney();
			int seedId = seedBag.getSeedId();
			// 获取单价
			Seed seed = seedDAO.findBySeedId(seedId);
			int seedPurchasePrice = seed.getSeedPurchasePrice();
			if(money < seedPurchasePrice) {
				message.setMsg("金币不足！");
			}else {
				
				int userId = (int)user.getId();
				SeedBag findSeedBag = seedBagDAO.findByUserIdAndSeedId(userId, seedId);
				if(findSeedBag == null) {
					// 数据库不存在seedBag信息
					seedBag.setUserId(userId);
					seedBag.setSeedId(seedId);
					seedBag.setNumber(1);
					seedBagDAO.save(seedBag);
				}else {
					findSeedBag.setNumber(findSeedBag.getNumber() + 1);
					seedBagDAO.save(findSeedBag);
				}
				
				money = money - seedPurchasePrice;
				user.setMoney(money);
				userDAO.save(user);
				message.setMsg("种子购买成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.setMsg("种子购买失败！");
		}
		
		return message;
	}

}
	